<?php

// 在文件顶部添加tinywan\JWT类引用
namespace app\api\controller;

use app\common\model\Merchant as MerchantModel;
use app\common\model\VerifyCode;
use think\Controller;
use think\exception\ValidateException;
use think\Log;
use think\Validate;
use tinywan\JWT; // 添加这一行
use think\Db;

class Merchant extends Controller
{
    /**
     * 商家注册
     */
    public function register()
    {
        $phone = $this->request->post('phone');
        $code = $this->request->post('code');
        $password = $this->request->post('password');

        if (!$phone || !$code) {
            $this->error(__('Invalid parameters'));
        }

        if (!Validate::regex($phone, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        // 验证密码
        if (!$password || !Validate::length($password, 6, 20)) {
            $this->error(__('Password must be between 6 and 20 characters'));
        }

        // 验证验证码
        $verifyCodeModel = new VerifyCode();
        $verifyResult = $verifyCodeModel->verifyCode($phone, $code, 'register');

        if (!$verifyResult['code']) {
            $this->error($verifyResult['msg']);
        }

        try {
            // 检查手机号是否已注册
            $exist = MerchantModel::where('phone', $phone)->find();
            if ($exist) {
                return json(['code' => 0, 'msg' => '该手机号已注册']);
            }

            // 创建商家数据
            $merchant = new MerchantModel();
            $merchant->phone = $phone;
            $merchant->password = $password; // 让模型的修改器自动加密
            $merchant->merchant_id = $merchant->generateMerchantId();
            $merchant->status = 1; // 账号状态
            $merchant->verification_status = 0; // 审核状态 0待审核 1审核通过 2审核不通过
            $merchant->save();

            return json(['code' => 1, 'msg' => '注册成功，请认证', 'data' => ['merchant_id' => $merchant->merchant_id]]);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        } catch (\Exception $e) {
            Log::error('商家注册失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '注册失败，请稍后再试']);
        }
    }

    /**
     * 商家登录
     */
    public function login()
    {
        $data = $this->request->param();
        try {
            // 验证数据
            $this->validate($data, [
                'phone' => 'require|regex:/^1[3-9]\d{9}$/',
                'password' => 'require|length:6,20',
            ]);

            // 查找商家
            $merchant = MerchantModel::where('phone', $data['phone'])->find();  

            if (!$merchant) {
                return json(['code' => 0, 'msg' => '账号不存在']);
            }

            // 检查密码
            if (!password_verify($data['password'], $merchant->password)) {
                return json(['code' => 0, 'msg' => '密码错误']);
            }

            // 更新最后登录时间
            $merchant->last_login_time = date('Y-m-d H:i:s');
            $merchant->save();

            // 生成JWT令牌 - 使用tinywan\JWT类的generateToken方法
            $tokenData = JWT::generateToken([
                'id' => $merchant->id, // 必需的唯一标识
                'phone' => $merchant->phone,
                'access_exp' => 3600 * 24 * 7, // 有效期7天
                'extend' => [ // 扩展信息
                    'merchant_id' => $merchant->merchant_id,
                    'phone' => $merchant->phone
                ]
            ]);

            return json([
                'code' => 1,
                'msg' => '登录成功',
                'data' => [
                    'token' => $tokenData['access_token'],
                    'id' => $merchant->id,
                    'merchant_id' => $merchant->merchant_id,
                    'phone' => $merchant->phone
                ]
            ]);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        } catch (\Exception $e) {
            Log::error('商家登录失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '登录失败，请稍后再试']);
        }
    }

    /**
     * 获取商家信息
     */
    public function getInfo()
    {
        try {
           // 验证令牌，确保用户已登录
           $tokenInfo = JWT::verify();

           // 正确获取商家ID：从extend数组中获取
           $merchantId = $tokenInfo['extend']['id'];
           
           // 查找商家信息
           $merchant = MerchantModel::where('id', $merchantId)->find();

           if (!$merchant) {
               return json(['code' => 0, 'msg' => '商家不存在']);
           }

           // 构建返回数据
           $data = [
               'id' => $merchant->id,
               'merchant_id' => $merchant->merchant_id,
               'phone' => $merchant->phone,
               'status' => $merchant->status,
               'verification_status' => $merchant->verification_status,
               'created_at' => $merchant->created_at,
               'updated_at' => $merchant->updated_at
           ];

           return json(['code' => 1, 'msg' => '获取成功', 'data' => $data]);
        } catch (\Exception $e) {
           return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 商家认证文件上传
     * @ApiMethod (POST)
     * @ApiParams (name="file", type="file", required=true, description="文件流")
     */
    public function upload()
    {
        try {
            // 验证token
            $tokenInfo = JWT::verify();

            // 从extend数组获取商家ID
            $merchantId = $tokenInfo['extend']['id'];
            if (empty($merchantId)) {
                return json(['code' => 1, 'msg' => '无法获取商家ID', 'data' => []]);
            }

            // 文件上传逻辑...
            $chunkid = $this->request->param('chunkid', 0);
            if ($chunkid) {
                // 分片上传逻辑
                // ... existing code ...
            } else {
                // 普通上传逻辑
                // 获取上传文件
                $file = $this->request->file('file');
                if (empty($file)) {
                    return json(['code' => 1, 'msg' => '请选择上传文件', 'data' => []]);
                }

                // 移动文件到uploads目录
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                    // 获取域名
                    $domain = request()->domain();
                    // 构建完整URL，将反斜杠替换为正斜杠
                    $fileUrl = $domain . '/uploads/' . str_replace('\\', '/', $info->getSaveName());
                    
                    $result = [
                        'file_path' => $fileUrl,  // 返回完整URL
                        'file_name' => $info->getFilename(),
                        'file_size' => $info->getSize()
                    ];
                    return json(['code' => 0, 'msg' => '上传成功', 'data' => $result]);
                } else {
                    return json(['code' => 1, 'msg' => $file->getError(), 'data' => []]);
                }
            }
        } catch (JWTTokenExpiredException $e) {
            // 处理令牌过期异常
            return json(['code' => 401, 'msg' => '身份验证会话已过期，请重新登录', 'data' => []]);
        } catch (Exception $e) {
            // 处理其他异常
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    
    /**
     * 商家信息认证接口
     * @return json
     */
    public function authInfo()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $id = $tokenInfo['extend']['id'];
            $merchantId = $tokenInfo['extend']['extend']['merchant_id'];

            // 查询商家是否存在
            $merchant = MerchantModel::where('id', $id)->find();
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商家不存在', 'data' => []]);
            }
    
            // 获取请求参数（文件路径由上传接口返回）
            $data = [
                'merchant_id' => $merchantId,
                'store_name' => $this->request->param('store_name'),
                'store_logo' => $this->request->param('store_logo'), // 已上传的文件路径
                'store_phone' => $this->request->param('store_phone'),
                'province' => $this->request->param('province'),
                'city' => $this->request->param('city'),
                'district' => $this->request->param('district'),
                'address' => $this->request->param('address'),
                'verification_status' => 1, // 审核中
                'business_license' => $this->request->param('business_license'), // 已上传的文件路径
                'id_card_front' => $this->request->param('id_card_front'), // 已上传的文件路径
                'id_card_back' => $this->request->param('id_card_back'), // 已上传的文件路径
                'other_qualification' => $this->request->param('other_qualification'), // 多个文件路径用逗号分隔
                'created_at' => time(),
                'updated_at' => time(),
            ];
    
            // 数据验证
            $validate = new \app\common\validate\MerchantAuth();
            if (!$validate->check($data)) {
                return json(['code' => 0, 'msg' => $validate->getError(), 'data' => []]);
            }
    
            // 将商家审核信息插入审核表
            $insertId = Db::name('merchant_audit')->insertGetId($data);
            if (!$insertId) {
                throw new Exception('提交审核失败');
            }
    
            return json(['code' => 1, 'msg' => '信息提交成功，等待审核', 'data' => []]);
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '令牌已过期', 'data' => []]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 获取商家认证信息
     * @return json
     */
    public function getAuthInfo()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $id = $tokenInfo['extend']['id'];
            $merchantId = $tokenInfo['extend']['extend']['merchant_id'];
            
            // 查询商家是否存在
            $merchant = MerchantModel::where('id', $id)->find();
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商家不存在', 'data' => []]);
            }
            
            // 查询商家认证信息
            $authInfo = Db::name('merchant_audit')
                ->where('merchant_id', $merchantId)
                ->order('id', 'desc')
                ->find();
                
            if (!$authInfo) {
                return json(['code' => 0, 'msg' => '未找到认证信息', 'data' => []]);
            }
            
            return json(['code' => 1, 'msg' => '获取成功', 'data' => $authInfo]);
            
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '令牌已过期', 'data' => []]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 编辑商家认证信息
     * @return json
     */
    public function editAuthInfo()
    {
        try {
            // JWT验证
            $tokenInfo = JWT::verify();
            $id = $tokenInfo['extend']['id'];
            $merchantId = $tokenInfo['extend']['extend']['merchant_id'];
            
            // 查询商家是否存在
            $merchant = MerchantModel::where('id', $id)->find();
            if (!$merchant) {
                return json(['code' => 0, 'msg' => '商家不存在', 'data' => []]);
            }
            
            // 开启事务
            Db::startTrans();
            
            try {
                // 查询商家最新认证信息
                $authInfo = Db::name('merchant_audit')
                    ->where('merchant_id', $merchantId)
                    ->order('id', 'desc')
                    ->find();
                    
                if (!$authInfo) {
                    return json(['code' => 0, 'msg' => '未找到认证信息，请先提交认证', 'data' => []]);
                }
                
                // 获取请求参数（文件路径由上传接口返回）
                $updateData = [];
                
                // 只更新传递的参数
                if ($this->request->param('store_name') !== null) {
                    $updateData['store_name'] = $this->request->param('store_name');
                }
                if ($this->request->param('store_logo') !== null) {
                    $updateData['store_logo'] = $this->request->param('store_logo');
                }
                if ($this->request->param('store_phone') !== null) {
                    $updateData['store_phone'] = $this->request->param('store_phone');
                }
                if ($this->request->param('province') !== null) {
                    $updateData['province'] = $this->request->param('province');
                }
                if ($this->request->param('city') !== null) {
                    $updateData['city'] = $this->request->param('city');
                }
                if ($this->request->param('district') !== null) {
                    $updateData['district'] = $this->request->param('district');
                }
                if ($this->request->param('address') !== null) {
                    $updateData['address'] = $this->request->param('address');
                }
                if ($this->request->param('business_license') !== null) {
                    $updateData['business_license'] = $this->request->param('business_license');
                }
                if ($this->request->param('id_card_front') !== null) {
                    $updateData['id_card_front'] = $this->request->param('id_card_front');
                }
                if ($this->request->param('id_card_back') !== null) {
                    $updateData['id_card_back'] = $this->request->param('id_card_back');
                }
                if ($this->request->param('other_qualification') !== null) {
                    $updateData['other_qualification'] = $this->request->param('other_qualification');
                }
                
                // 设置状态和时间
                $updateData['verification_status'] = 0; // 待审核
                $updateData['updated_at'] = time();
                
                // 直接更新最新的认证记录，而不是插入新记录
                $result = Db::name('merchant_audit')
                    ->where('id', $authInfo['id'])
                    ->update($updateData);
                
                if (!$result) {
                    throw new Exception('提交审核失败');
                }
                
                // 同时更新商家表的审核状态为待审核
                $merchantUpdateResult = Db::name('merchant')
                    ->where('merchant_id', $merchantId)
                    ->update([
                        'verification_status' => 0, // 待审核
                        'updated_at' => time(),
                    ]);
                
                if ($merchantUpdateResult === false) {
                    throw new Exception('更新商家状态失败');
                }
                
                // 提交事务
                Db::commit();
                
                return json(['code' => 1, 'msg' => '认证信息已提交更新，状态已重置为待审核', 'data' => []]);
                
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
            
        } catch (JWTTokenExpiredException $e) {
            return json(['code' => 401, 'msg' => '令牌已过期', 'data' => []]);
        } catch (Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
}

